package com.ihealthway.all.groupbuy.services;

import com.ihealthway.all.utils.Ajax;
import com.ihealthway.all.utils.AjaxReturn;
import com.ihealthway.all.groupbuy.vo.MPSetting;
import io.github.elkan1788.mpsdk4j.api.WechatAPIImpl;
import io.github.elkan1788.mpsdk4j.vo.api.AccessToken;
import io.github.elkan1788.mpsdk4j.vo.api.JSTicket;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.Date;

/**
 * Wechat MP setting service
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean(fields = {"dao"})
public class MPSettingService extends BaseService<MPSetting> {

    private static final Log logger = Logs.get();

    @Inject
    private WechatAPIImpl wechatAPI;

    public MPSetting get() {
        MPSetting mp = get("data_status", "0");
        logger.infof("MP Setting: %s", mp);
        return mp;
    }

    public AjaxReturn update(MPSetting setting) {

        AjaxReturn ar = Ajax.ok();
        setting.setUpdateTime(new Date());
        try {
            int effectRows = dao().updateIgnoreNull(setting);
            logger.infof("Update MPSetting effect rows: %s", effectRows);
            if (effectRows == 0) {
                ar.setOk(false);
            }
        } catch (Exception e) {
            logger.error("Update MPSetting info failed.", e);
            ar.setOk(false);
        }

        return ar;
    }

    public void  refreshWechatAllToken() {

        MPSetting mpSet = get();

        String accessToken = mpSet.getAccessToken();
        long atExpireTime = mpSet.getAtExpireTime()==null ? 0 : mpSet.getAtExpireTime().longValue();
        AccessToken at = new AccessToken(accessToken, atExpireTime);

        boolean update = false;

        // Add exist access token int memory cache
        if (at.isAvailable()) {
            logger.infof("Access token will alive until: %s", new Date(atExpireTime).toString());
            WechatAPIImpl.getAccessTokenCache().set(mpSet.getMpId(), at);
        } else {
            logger.infof("Refresh access token info...");

            update = true;
            accessToken = wechatAPI.getAccessToken();
            atExpireTime = wechatAPI.getAccessTokenExpireTime();

            mpSet.setAccessToken(accessToken);
            mpSet.setAtExpireTime(atExpireTime);
        }

        String jsTicket = mpSet.getJsTicket();
        long jtExpireTime = mpSet.getJtExpireTime()==null ? 0 : mpSet.getJtExpireTime().longValue();
        JSTicket jt = new JSTicket(jsTicket, jtExpireTime);

        // Add exist js ticket int memory cache
        if (jt.isAvailable()) {
            logger.infof("JS ticket will alive until: %s", new Date(jtExpireTime).toString());
            WechatAPIImpl.getJsTicketCache().set(mpSet.getMpId(), jt);
        } else {
            logger.infof("Refresh js sdk ticket info...");

            update = true;
            jsTicket = wechatAPI.getJSTicket();
            jtExpireTime = wechatAPI.getJSTicketExpireTime();

            mpSet.setJsTicket(jsTicket);
            mpSet.setJtExpireTime(jtExpireTime);
        }

        if (update)  {
            logger.infof("Update MP setting info...");
            mpSet.setUpdateTime(new Date());
            update(mpSet);
        }
    }

}
